<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    v-if="load"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="700"
    @close="close"
    :z-index="2000"
  >
    <!-- 设计审核 -->
    <template v-if="pictureType == 'designReview'">
      <el-form :model="form" label-position="top" @keydown.enter.stop @submit.prevent>
        <el-form-item label="">
          <div class="text-base">
            选中单据: <span style="color: #3366f1">{{ checkedList.length }}</span>
          </div>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1" size="large">审核通过</el-radio>
            <el-radio label="2" size="large">审核未通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-checkbox
          v-if="form.status == 1"
          class="-mt-1"
          v-model="form.is_operator_pass"
          :true-label="1"
          :false-label="0"
          :label="'同步运营审核通过'"
          size="large"
        />
        <el-form-item label="设计评分">
          <el-input v-model="form.score" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input
            v-model="form.comment"
            :rows="2"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
    </template>
    <!-- 运营审核 -->
    <template v-if="pictureType == 'operationAudit'">
      <el-form :model="form" label-position="top" @keydown.enter.stop @submit.prevent>
        <el-form-item label="">
          <div class="text-base">
            选中单据: <span style="color: #3366f1">{{ checkedList.length }}</span>
          </div>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-radio-group class="w-full" v-model="form.status">
            <el-radio label="1" size="large">审核通过</el-radio>
            <el-radio label="2" size="large">审核未通过</el-radio>
          </el-radio-group>
          <el-checkbox
            v-if="form.status == 1"
            class="-mt-1"
            v-model="form.task_status"
            :true-label="1"
            :false-label="0"
            :label="'直接审核完成'"
            size="large"
          />
        </el-form-item>
        <el-form-item label="运营评分">
          <el-input v-model="form.score" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input
            v-model="form.comment"
            :rows="2"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
    </template>
    <template v-if="pictureType == 'haveReviewed'">
      <el-form :model="form" label-position="top" @keydown.enter.stop @submit.prevent>
        <el-form-item label="">
          <div class="text-base">
            选中单据: <span style="color: #3366f1">{{ checkedList.length }}</span>
          </div>
        </el-form-item>
        <el-form-item label="设计审核人">
          <select-personnel
            class="w-full"
            v-model="form.designer_reviewer"
            placeholder="添加人"
          ></select-personnel>
        </el-form-item>
      </el-form>
      <div class="flex items-center" style="margin-top: 4px; color: #9da1ad">
        <svg-icon icon-class="hint_cover2"></svg-icon>
        “待设计审核”与“待运营审核”的任务不允许同时操作审核！
      </div>
    </template>
    <template v-if="pictureType == 'batchDistriBution'">
      <el-form :model="form" label-position="top" @keydown.enter.stop @submit.prevent>
        <el-row :gutter="21">
          <el-col :span="12">
            <el-form-item label="图片处理人员">
              <select-personnel
                class="w-full"
                v-model="form.designer_user"
                placeholder="请选择"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="摄影人员">
              <select-personnel
                class="w-full"
                v-model="form.photography_user"
                placeholder="请选择"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编辑人员">
              <select-personnel
                class="w-full"
                v-model="form.edit_user"
                placeholder="请选择"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渲染人员">
              <select-personnel
                class="w-full"
                v-model="form.render_user"
                placeholder="请选择"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="协助人员">
              <select-personnel
                class="w-full"
                v-model="form.assistance_user"
                placeholder="请选择"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门分配周期">
              <el-date-picker
                v-model="form.assignment_time"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="defaultTimeRang()"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template v-if="pictureType == 'uploadEdit'">
      <FileUpload v-model="attachments" />
    </template>
    <template v-if="pictureType == 'makeTag' || pictureType == 'makeTagPerformance'">
      <el-form :model="form" label-position="top">
        <el-form-item label="标签绑定角色" required>
          <el-select
            v-model="form.ruleType"
            collapse-tags
            placeholder="标签绑定角色"
            clearable
            class="w-full"
          >
            <el-option
              v-for="item of options['assignment.ImagesTag']?.[0].ruleTypeText"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-row :gutter="21">
          <el-col :span="12">
            <el-form-item label="图片任务标签" required>
              <SelectImagesTag
                class="w-full"
                v-model="form.imagesTagId"
                placeholder="请选择标签"
                @changeItem="changeItem"
              >
              </SelectImagesTag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签数量" required>
              <el-input v-model="form.tagCount" placeholder="请输入标签数量"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- <div style="margin-top: 4px; color: #9da1ad" v-if="pictureType == 'makeTag'">
        说明：此标签将用于绩效计算；图片处理、摄影、编辑、渲染、协助人员，在协助处理非处理图片设计类型的工作时，标记标签后进行绩效统计（例如需摄影、文案编辑、模特等）；相应任务重对应角色需维护具体员工，此绑定才会生效
      </div> -->
      <div style="margin-top: 4px; color: #9da1ad">
        <p>说明：</p>
        <p>1、此标签将用于设计绩效计算；</p>
        <p>2、只有所选角色有维护人员，此标签才会生效；</p>
        <p>3、同一个标签支持重复标记，对应分数也会重复计算，调整标签数量即可；</p>
      </div>
    </template>
    <template v-if="pictureType == 'allocateTime'">
      <div class="min-h-[200px]">
        <el-form :model="form" label-position="top">
          <el-form-item label="任务完成周期" required>
            <el-date-picker
              v-model="form.assignmentTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="defaultTimeRang()"
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template v-if="pictureType == 'taskDemand'">
      <el-form :model="form" label-position="top">
        <el-row :gutter="21">
          <el-col :span="12">
            <el-form-item label="任务等级/类型">
              <VGroup>
                <el-select
                  v-model="form.task_priority"
                  class="w-40"
                  placeholder="请选择任务等级"
                  clearable
                >
                  <el-option
                    v-for="item in options['assignment.ImagesAssignment']?.[0]
                      .taskPriorityText"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                <SelectTaskTypeByUid
                  v-model="form.task_type"
                  placeholder="请选择任务类型"
                  multiple
                  clearable
                ></SelectTaskTypeByUid>
                <!-- <el-select v-model="form.task_type" placeholder="请选择任务类型" multiple clearable>
                  <el-option v-for="item in options['assignment.ImagesAssignment']?.[0].taskTypeText" :key="item.value"
                    :label="item.label" :value="item.value"></el-option>
                </el-select> -->
              </VGroup>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务优先级">
              <el-select
                class="w-full"
                v-model="form.priority"
                placeholder="请选择任务优先级"
                clearable
              >
                <el-option
                  v-for="item in options['assignment.ImagesAssignment']?.[0].priorityText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设计品牌">
              <select-brand
                class="w-full"
                v-model="form.brand_id"
                :multiple="true"
                placeholder="设计品牌"
              ></select-brand>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预期完成时间">
              <el-date-picker
                style="width: 100%"
                :disabled-date="UtilEleDisabledDay"
                :disabled-hours="UtilEleDisabledHour"
                :disabled-minutes="UtilEleDisabledMinute"
                :disabled-seconds="UtilEleDisabledSecond"
                v-model="form.expected_time"
                type="datetime"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品类型">
              <el-select
                class="w-full"
                v-model="form.product_type"
                placeholder="产品类型"
                clearable
              >
                <el-option
                  v-for="item in options['assignment.ImagesAssignment']?.[0]
                    .productTypeText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图片数量">
              <el-select
                class="w-full"
                v-model="form.image_total"
                placeholder="产品类型"
                clearable
              >
                <el-option
                  v-for="item in options['assignment.ImagesAssignment']?.[0]
                    .imageTotalText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务备注">
              <el-input
                v-model="form.task_remark"
                :rows="2"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template v-if="pictureType == 'performanceMonth'">
      <el-form :model="form" label-position="top" @keydown.enter.stop @submit.prevent>
        <el-form-item label="请选择绩效月份">
          <el-date-picker
            style="width: 100%"
            v-model="form.performanceMonth"
            type="month"
            value-format="YYYY-MM-DD"
            placeholder="请选择月份"
          />
        </el-form-item>
      </el-form>
    </template>
    <template v-if="pictureType == 'setPersonnel'">
      <el-form :model="form" label-position="top" @keydown.enter.stop @submit.prevent>
        <el-row :gutter="21">
          <el-col :span="12">
            <el-form-item label="开发人员">
              <select-personnel
                class="w-full"
                v-model="form.developer_user"
                placeholder="请选择"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运营人员">
              <select-personnel
                class="w-full"
                v-model="form.operators_user_ids"
                placeholder="请选择"
                :multiple="true"
              ></select-personnel>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template v-if="pictureType == 'setExcessTask'">
      <el-form :model="form" label-position="left">
        <el-form-item class="items-center" label="是否超额任务" required>
          <el-radio-group v-model="form.is_exceed_task">
            <el-radio :label="1" size="large">是</el-radio>
            <el-radio :label="0" size="large">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="text-[#999999]">
        注：设置为超额任务，则设计人效报表中的交付完成率不计算该任务；
      </div>
    </template>

    <template v-if="pictureType == 'cancel'">
      <div class="text-lg">
        <div>
          选中单据：<span class="text-[#E50113]">{{ checkedList.length }}</span>
        </div>
        <div>是否确认取消图片任务？</div>
      </div>
      <div class="text-[#999999]">
        说明：只允许取消状态为“待设计审核”、“审核未通过”的任务
      </div>
    </template>

    <template #footer>
      <el-checkbox
        v-if="pictureType == 'batchDistriBution' || pictureType == 'haveReviewed'"
        class="-mt-1"
        v-model="form.is_notify"
        :true-label="1"
        :false-label="0"
        :label="
          pictureType == 'batchDistriBution'
            ? '消息通知处理人员、创建人员'
            : pictureType == 'designReview' || pictureType == 'operationAudit'
            ? '消息通知产品开发、设计人员'
            : pictureType == 'haveReviewed'
            ? '通知所选审核人员'
            : ''
        "
        size="large"
      />
      <template v-if="pictureType == 'designReview'">
        <template v-if="batchFalge == 3">
          <el-checkbox
            class="-mt-1"
            v-model="form.is_notify"
            :true-label="1"
            :false-label="0"
            :label="'消息通知运营人员、设计人员'"
            size="large"
          />
        </template>
        <template v-if="batchFalge == 4">
          <span class="mr-[8px]">消息通知: </span
          ><el-checkbox
            class="-mt-1"
            v-model="form.design_notify"
            :true-label="1"
            :false-label="0"
            :label="'设计人员'"
            size="large"
          />
          <el-checkbox
            class="-mt-1"
            v-model="form.developer_notify"
            :true-label="1"
            :false-label="0"
            :label="'产品开发'"
            size="large"
          />
        </template>
      </template>
      <el-button class="ml-5" @click="close">取消</el-button>
      <el-button type="primary" @click="serveFun">提交</el-button>
    </template>
  </el-dialog>
</template>

<script name="pictureDialog" setup>
import { reactive, toRefs } from "vue";
import {
  batchDesignReview,
  batchOperateReview,
  batchAssignment,
  submitReview,
  uploadCopywriting,
  batchMarkTag,
  batchSetTime,
  batchSetPerformanceMonth,
  batchSetTask,
  batchaAssignment,
  setExceed,
  cancelTask,
} from "../api";
import FileUpload from "./FileUpload.vue";
import { ElMessage } from "element-plus";
import SelectImagesTag from "@/components/SelectImagesTag";
import SelectBrand from "@/components/SelectBrand";
import SelectTaskTypeByUid from "@/components/Selects/SelectTaskTypeByUid/index.vue";

const attachments = ref([]);

const data = reactive({
  dialogVisible: false,
  title: "",
  pictureType: null,
  checkedList: [],
  form: {},
  load: false,
});

let options = reactive(inject("options"));

const { dialogVisible, title, pictureType, checkedList, form, load } = toRefs(data);

const operationType = new Map([
  ["batchDistriBution", "批量分配人员"],
  ["designReview", "设计审批"],
  ["operationAudit", "运营审批"],
  ["haveReviewed", "提交审核"],
  ["uploadEdit", "上传编辑文案"],
  ["allocateTime", "批量设置分配完成周期"],
  ["taskDemand", "批量设置任务要求"],
  ["performanceMonth", "批量设置绩效月份"],
  ["makeTag", "标记图片任务标签"],
  ["makeTagPerformance", "标记图片任务标签"],
  ["setPersonnel", "设置人员"],
  ["setExcessTask", "设置超额任务"],
  ["cancel", "取消"],
]);

const disabledDate = (time) => {
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth() + 1;
  const selectedYear = time.getFullYear();
  const selectedMonth = time.getMonth() + 1;

  // 只允许选择当前月和上个月的日期，包括跨年情况
  return (
    !(
      selectedYear === currentYear &&
      (selectedMonth === currentMonth || selectedMonth === currentMonth - 1)
    ) && !(selectedYear === currentYear - 1 && selectedMonth === 12)
  );
};

const batchFalge = ref(null);
const open = async (type, records, falge) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  if (type == "designReview" || type == "operationAudit") {
    batchFalge.value = falge;
  }
  title.value = operationType.get(type);
  pictureType.value = type;
  checkedList.value = records;
  form.value.design_notify = 0;
  if (type == "haveReviewed" || type == "batchDistriBution") {
    form.value.is_notify = 1;
  } else {
    form.value.is_notify = 0;

    if (type == "makeTag") {
      form.value.tagCount = 1;
    }
  }
  if (type == "designReview" && falge == 3) {
    form.value.is_notify = 1;
  }
  if (type == "operationAudit" && falge == 4) {
    form.value.design_notify = 1;
  }
  dialogVisible.value = true;
};

const close = () => {
  form.value = {};
  dialogVisible.value = false;
};

const serveFun = () => {
  const id = checkedList.value;
  const formData = Object.assign({}, form.value);

  switch (pictureType.value) {
    // 批量分配人员
    case "batchDistriBution":
      if (formData.assignment_time?.length > 0) {
        formData.assignment_time_start = formData.assignment_time[0];
        formData.assignment_time_end = formData.assignment_time[1];
      }
      const filterForm = {
        designer_user: formData.designer_user,
        photography_user: formData.photography_user,
        edit_user: formData.edit_user,
        render_user: formData.render_user,
        assistance_user: formData.assistance_user,
      };

      let key_values = Object.values(filterForm);
      if (!key_values.some((i) => i)) {
        ElMessage.error("至少给其中一个角色维护人员");
        return;
      }

      batchAssignment({
        // 分配人员
        id,
        ...formData,
      }).then(() => {
        ElMessage({
          message: "批量分配人员处理成功",
          type: "success",
        });
        close();
      });
      break;
    // 批量设计审批
    case "designReview":
      batchDesignReview({
        // 批量审核
        id,
        ...form.value,
      }).then(() => {
        ElMessage({
          message: "批量审批处理成功",
          type: "success",
        });
        close();
      });
      break;
    // 批量运营审核
    case "operationAudit":
      batchOperateReview({
        // 批量审核
        id,
        ...form.value,
      }).then(() => {
        ElMessage({
          message: "批量审批处理成功",
          type: "success",
        });
        close();
      });
      break;
    // 提交审核
    case "haveReviewed":
      if (!form.value.designer_reviewer) {
        ElMessage.error("请选择设计审核人员");
        return;
      }
      submitReview({
        // 提交审核
        id,
        ...form.value,
      }).then(() => {
        ElMessage({
          message: "提交审核处理成功",
          type: "success",
        });
        close();
      });
      break;

    // 上传编辑文案
    case "uploadEdit":
      uploadCopywriting({
        //上传编辑文案
        text_file: attachments._rawValue, //文件地址
        id: id[0],
      }).then(() => {
        ElMessage({
          message: "上传编辑文案处理成功",
          type: "success",
        });
        attachments.value = [];
        close();
      });
      break;
    case "makeTag":
      if (!form.value.tagCount) {
        ElMessage.error("标签数量必须大于0");
        return;
      }
      if (!form.value.imagesTagId) {
        ElMessage.error("请选择任务标签");
        return;
      }
      //
      batchMarkTag({
        ...form.value,
        taskIds: id,
      }).then(() => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        close();
      });
      break;
    case "makeTagPerformance":
      if (!form.value.tagCount) {
        ElMessage.error("标签数量必须大于0");
        return;
      }
      if (!form.value.imagesTagId) {
        ElMessage.error("请选择任务标签");
        return;
      }
      emit("success", form.value);
      close();
      break;
    case "allocateTime":
      if (formData.assignmentTime.length > 0) {
        formData.assignmentTimeStart = formData.assignmentTime[0];
        formData.assignmentTimeEnd = formData.assignmentTime[1];
      }
      batchSetTime({
        ...formData,
        taskIds: id,
      }).then(() => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        close();
      });
      break;
    case "performanceMonth":
      batchSetPerformanceMonth({
        ...formData,
        taskIds: id,
      }).then(() => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        close();
      });
      break;
    case "taskDemand":
      batchSetTask({
        requirements: formData,
        taskIds: id,
      }).then(() => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        close();
      });
      break;
    case "setPersonnel":
      batchaAssignment({
        ...formData,
        id,
      }).then(() => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        close();
      });
      break;
    case "setExcessTask":
      setExceed({
        ...formData,
        task_id: id,
      }).then(() => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        emit("query");
        close();
      });
      break;
    case "cancel":
      cancelTask({
        id,
      }).then(() => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        emit("query");
        close();
      });
      break;
  }
};

const emit = defineEmits(["close", "query", "success"]);

defineExpose({ open });

const changeItem = (item) => {
  if ([pictureType == "makeTagPerformance"]) {
    form.value.tag_name = item.tag_name;
    form.value.score = item.score;
    form.value.is_auto_relation = item.is_auto_relation;
    form.value.is_auto_relation_text = item.is_auto_relation_text;
  }
};

const defaultTimeRang = () => {
  return [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 2, 1, 23, 59, 59)];
};
</script>
<style lang="scss">
// .dialog-content {
//   .el-dialog__body {
//     min-height: 200px;
//   }
// }
</style>
